package com.gsp.framework.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropsUtil {
    private static final Logger log = LoggerFactory.getLogger(PropsUtil.class);

    /**
     * 加载属性文件
     *
     * @param fileName
     * @return
     */
    public static Properties loadProps(String fileName) {
        Properties prop = null;
        InputStream in = null;
        prop = new Properties();
        try {
            in = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
            if (in == null) {
                throw new FileNotFoundException(fileName + " file is not found");
            }
            prop.load(in);
        } catch (IOException e) {
            log.error("load properties is error", e);
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                log.error("close file error", e);
            }
        }
        return prop;
    }

    public static String getString(Properties prop, String key) {
        return getString(prop, key, "");
    }

    public static String getString(Properties prop, String key, String defaultValue) {
        return prop.getProperty(key, defaultValue);
    }

    public static int getInt(Properties prop, String key) {
        return getInt(prop, key, 0);
    }

    public static int getInt(Properties prop, String key, int defaultValue) {
        return CastUtil.castInt(prop.getProperty(key), defaultValue);
    }

    public static double getDouble(Properties prop, String key) {
        return getDouble(prop, key, 0.0);
    }

    public static double getDouble(Properties prop, String key, double defaultValue) {
        return CastUtil.castDouble(prop.getProperty(key), defaultValue);
    }

    public static boolean getBoolean(Properties prop, String key) {
        return getBoolean(prop, key, false);
    }

    public static boolean getBoolean(Properties prop, String key, boolean defaultValue) {
        return CastUtil.castBoolean(prop.getProperty(key), defaultValue);
    }


}
